package com.um.jdy.app.shop.factory.impl;

import cn.hutool.core.util.RandomUtil;
import com.um.jdy.app.shop.coupons.Coupons;
import com.um.jdy.app.shop.coupons.impl.CouponsImpl;
import com.um.jdy.app.shop.coupons.impl.GiftCouponsImpl;
import com.um.jdy.app.shop.coupons.impl.VoucherCouponsImpl;
import com.um.jdy.app.shop.entity.bo.CouponsBO;
import com.um.jdy.app.shop.factory.CouponsFactory;
import com.um.jdy.common.member.service.MemberUserService;
import com.um.jdy.common.shop.enums.CouponsEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 优惠券工厂实现类
 *
 * @author 邓南辉
 * 日期 2021/6/28
 * 版权所有 广州优匠科技有限公司
 */
@Service
@Transactional
public class CouponsFactoryImpl implements CouponsFactory {

    @Autowired
    MemberUserService userService;

    @Autowired
    AutowireCapableBeanFactory beanFactory;

    @Autowired
    DefaultListableBeanFactory defaultListableBeanFactory;

    @Override
    public List<Coupons> createCoupons() {
        List<Coupons> couponsList = new ArrayList();

        List<CouponsBO> list = userService.getViewModelList("get_my_usable_coupons_list", CouponsBO.class, new Object[]{userService.get().getMemberUserId(),userService.getComId()});
        for(CouponsBO couponsBO : list){
            if(CouponsEnum.Type.Code.name().equals(couponsBO.getType())){ //兑换码不计入
                continue;
            }
            Coupons coupons = this.getCoupons(couponsBO);
            if(null != coupons){
                couponsList.add(coupons);
            }
        }

        return couponsList;
    }

    private Coupons getCoupons(CouponsBO couponsBO) {
        Coupons coupons;
        switch (CouponsEnum.Type.valueOf(couponsBO.getType())){
            case Coupons:
                coupons = new CouponsImpl();
                break;
            case Gift:
                coupons = new GiftCouponsImpl();
                break;
            case Voucher:
                coupons = new VoucherCouponsImpl();
                break;
            default:
                return null;
        }

        //将new出的对象放入Spring容器中注入依赖
        if(null != coupons){
            String beanName = System.currentTimeMillis() + "-" + RandomUtil.randomInt(10000);
            defaultListableBeanFactory.registerSingleton(beanName,coupons);
            beanFactory.autowireBean(coupons);
        }

        coupons.setCouponsEntity(couponsBO);
        return coupons;
    }
}
